package com.example.recyclerviewtest;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;

import java.util.HashMap;
import java.util.List;

/**
 * 可以对数据的某个属性进行排序的view
 */
public class ClassifyRecyclerview extends LinearLayout {
    private RecyclerView rec;
    //侧边栏
    private RadioGroup tab;
    //保存侧边栏字母位置信息的map
    private HashMap<String,Integer> indexMap;
    //recyclerview的适配器
    private RecAdapter recAdapter;
    //侧边栏是否允许点击，recyclerview活动期间不允许点击
    private boolean isRecMove = false;
    private LinearLayoutManager llm;
    //数据源
    private List<TestBeam> testBeams;
    //点击侧边栏显示的view
    private TextView alert;
    //主要用于延时操作
    private Handler handler;


    public ClassifyRecyclerview(Context context, AttributeSet attrs) {
        super(context, attrs);
        indexMap = new HashMap<>();
        handler = new Handler();
        initIndexMap();
        initView(context);
        initAdapter();
        initListener();
    }

    /**
     * 设置监听器
     */
    private void initListener() {
        final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);

        //recyclerview的滑动监听
        rec.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //如果recyclerview停止滑动状态，允许点击tab栏
                if (newState == 0){
                    isRecMove = false;
                }else {
                    isRecMove = true;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //滑动时获取屏幕第一条可见数据，并获取到此数据的行字首字母
                int position = llm.findFirstVisibleItemPosition();
                try{
                    //获取汉字首字母
                    String[] args = PinyinHelper.toHanyuPinyinStringArray(testBeams.get(position).getName().charAt(0), format);
                    //indexMap.get(String.valueOf(args[0].charAt(0)))为获取此条数据的汉字首字母在tab中的位置。
                    RadioButton radioButton = ((RadioButton)(tab.getChildAt(indexMap.get(String.valueOf(args[0].charAt(0))))));
                    radioButton.setChecked(true);
                }catch (Exception e){
                    Log.e("日志","错误");
                }

            }
        });

        //radiobutton的选中监听
        tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                try{
                    //如果是因为滑动recyclerview触发的，无需做任何处理，这里只处理右边tab点击时触发的事件
                    if (!isRecMove){
                        //获取点击位置的字母
                        String pinyin = ((RadioButton)(radioGroup.findViewById(radioGroup.getCheckedRadioButtonId()))).getText().toString();
                        if (recAdapter.getIndexMap().get(pinyin) != null){
                            int index = recAdapter.getIndexMap().get(pinyin);
                            //让recyclerview活动到对应的位置。recAdapter.getIndexMap().get(pinyin)是获取数据集合中第一条出现该字母数据的索引。
                            llm.scrollToPositionWithOffset(index,0);
                            llm.setStackFromEnd(true);
                        }
                        showOrHideAlert(pinyin);
                    }
                }catch (Exception e){
                    Log.e("日志","出现错误："+e.getLocalizedMessage());
                }
            }
        });
    }

    /**
     * 点击侧边栏时显示的提示
     * @param pinyin 要显示的字母
     */
    private void showOrHideAlert(String pinyin){
        alert.setText(pinyin);
        alert.setVisibility(VISIBLE);
        handler.removeMessages(0);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                alert.setVisibility(GONE);
            }
        },700);
    }


    /**
     * 初始化适配器
     */
    private void initAdapter() {
        recAdapter = new RecAdapter();
        llm = new LinearLayoutManager(getContext());
        rec.setLayoutManager(llm);
        rec.setAdapter(recAdapter);
        //设置条目之间的距离
       /* rec.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });*/
    }

    /**
     * 设置数据源
     * @param list 数据集合
     */
    public void setList(List<TestBeam> list){
        this.testBeams = list;
        recAdapter.setList(list);
    }

    /**
     * 将侧边栏的位置保存到hashmap中
     */
    private void initIndexMap() {
        indexMap.put("A",0);
        indexMap.put("B",1);
        indexMap.put("C",2);
        indexMap.put("D",3);
        indexMap.put("E",4);
        indexMap.put("F",5);
        indexMap.put("G",6);
        indexMap.put("H",7);
        indexMap.put("I",8);
        indexMap.put("J",9);
        indexMap.put("K",10);
        indexMap.put("L",11);
        indexMap.put("M",12);
        indexMap.put("N",13);
        indexMap.put("O",14);
        indexMap.put("P",15);
        indexMap.put("Q",16);
        indexMap.put("R",17);
        indexMap.put("S",18);
        indexMap.put("T",19);
        indexMap.put("U",20);
        indexMap.put("V",21);
        indexMap.put("W",22);
        indexMap.put("Y",23);
        indexMap.put("Z",24);
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.custom_recyclerview_classify,this,true);
        rec = findViewById(R.id.content);
        tab = findViewById(R.id.tab);
        alert = findViewById(R.id.alert);
    }


    public RecyclerView getRec(){
        return rec;
    }

    public RadioGroup getTab(){
        return tab;
    }
}
